# -*- coding: utf-8 -*-
# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
import os.path, sys
import fnmatch

sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/UI'))
from about import ShowAbout
from SelectPattern import GetPatternName
from Info import ShowObjectInfo

sys.path.append(os.path.abspath(os.path.dirname(__file__) + '/tools'))
from dodoc import *
import importxml as ix
from drawToQGIS import *
# from DrawGeometry import *

class landax:
    dir = ''
    iface = None
    canvas = None
    ps = ""

    def __init__(self, iface):
        if "Windows" in platform.system():
            ps = '\\'
        else:
            ps = '/'

        # Настройка логера сообщения типа logging.DEBUG  писать в файл
        if "Windows" in platform.system():
            fn = sys.path.append(os.path.dirname(__file__).decode('cp1251') + ps + u'mylog.log')
        else:
            fn = sys.path.append(os.path.dirname(__file__) + ps + u'mylog.log')
        logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=fn)
        logging.debug(u'Тестовое  сообщение landax')

        self.iface = iface
        self.canvas = iface.mapCanvas()

        # Включение локализации модуля
        self.transl = QTranslator()
        if "Windows" in platform.system():
            fn = os.path.dirname(__file__).decode('cp1251') + ps + 'i18n' + ps + 'landex_' + QLocale.system().name() + ".qm"
        else:
            fn = os.path.dirname(__file__) + ps + 'i18n' + ps + 'landex_' + QLocale.system().name() + ".qm"
        self.transl.load(fn)
        QCoreApplication.installTranslator(self.transl)
        QgsMessageLog.logMessage(fn)

    def initGui(self):
        # Create action that will start plugin
        self.actionHello = QAction(QIcon(":/plugins/landax/icons/icon.png"), "&Landax", self.iface.mainWindow())
        self.actionHello.setStatusTip("This is status tip")
        self.actionHello.setWhatsThis("Configuration for plugin")
        # connect the action to the run method
        QObject.connect(self.actionHello, SIGNAL("activated()"), self.hello_world)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu("Landax", self.actionHello)
        self.iface.addToolBarIcon(self.actionHello)

        # Create action for import exchangefile(s)
        self.actionOpenFile = QAction(QIcon("landax/icons/icon.png"), QApplication.translate("Toolbar", "&Import Exchange file"), self.iface.mainWindow())
        self.actionOpenFile.setStatusTip(QApplication.translate("Toolbar", "&Import Exchange file"))
        self.actionOpenFile.setWhatsThis(QApplication.translate("Toolbar", "&Import Exchange file"))
        # connect the action to the run method
        QObject.connect(self.actionOpenFile, SIGNAL("activated()"), self.open_file)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu("Landax", self.actionOpenFile)
        self.iface.addToolBarIcon(self.actionOpenFile)

        # Create action for import folder withexchangefiles
        self.actionOpenFolder = QAction(QIcon("landax/icons/icon.png"), QApplication.translate("Toolbar", "&Import Exchange files from folder"), self.iface.mainWindow())
        self.actionOpenFolder.setStatusTip(QApplication.translate("Toolbar", "&Import Exchange files from folder"))
        self.actionOpenFolder.setWhatsThis(QApplication.translate("Toolbar", "&Import Exchange files from folder"))
        # connect the action to the run method
        QObject.connect(self.actionOpenFolder, SIGNAL("activated()"), self.open_folder)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu("Landax", self.actionOpenFolder)
        self.iface.addToolBarIcon(self.actionOpenFolder)

        # Create action for SelectPattern dialog
        self.actionShowSelectPatternDialog = QAction(QIcon("landax/icons/icon.png"), QApplication.translate("Toolbar", "&Select pattern for project"), self.iface.mainWindow())
        self.actionShowSelectPatternDialog.setStatusTip(QApplication.translate("Toolbar", "&Select pattern for project"))
        self.actionShowSelectPatternDialog.setWhatsThis(QApplication.translate("Toolbar", "&Select pattern for project"))
        # connect the action to the run method
        QObject.connect(self.actionShowSelectPatternDialog, SIGNAL("activated()"), self.show_SelectPatternDialog)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu("Landax", self.actionShowSelectPatternDialog)
        self.iface.addToolBarIcon(self.actionShowSelectPatternDialog)

        # Create action for About dialog
        self.actionShowAboutDialog = QAction(QIcon("landax/icons/icon.png"), QApplication.translate("Toolbar", "&About"), self.iface.mainWindow())
        self.actionShowAboutDialog.setStatusTip(QApplication.translate("Toolbar", "&About"))
        self.actionShowAboutDialog.setWhatsThis(QApplication.translate("Toolbar", "&About"))
        # connect the action to the run method
        QObject.connect(self.actionShowAboutDialog, SIGNAL("activated()"), self.show_AboutDialog)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu("Landax", self.actionShowAboutDialog)
        self.iface.addToolBarIcon(self.actionShowAboutDialog)

        # Create action for ShowObjectInfo dialog
        self.actionShowObjectInfoDialog = QAction(QIcon("landax/icons/icon.png"), QApplication.translate("Toolbar", "&Information"), self.iface.mainWindow())
        self.actionShowObjectInfoDialog.setStatusTip(QApplication.translate("Toolbar", "&Information"))
        self.actionShowObjectInfoDialog.setWhatsThis(QApplication.translate("Toolbar", "&Information"))
        # connect the action to the run method
        QObject.connect(self.actionShowObjectInfoDialog, SIGNAL("activated()"), self.show_ObjectInfoDialog)

        # Add toolbar button and menu item
        self.iface.addPluginToMenu("Landax", self.actionShowObjectInfoDialog)
        self.iface.addToolBarIcon(self.actionShowObjectInfoDialog)

    def unload(self):
        # Remove the plugin menu items and icons
        self.iface.removePluginMenu("Landax", self.actionHello)
        QObject.disconnect(self.actionHello, SIGNAL("activated()"), self.hello_world)
        self.iface.removeToolBarIcon(self.actionHello)

        self.iface.removePluginMenu("Landax", self.actionOpenFile)
        QObject.disconnect(self.actionOpenFile, SIGNAL("activated()"), self.open_file)
        self.iface.removeToolBarIcon(self.actionOpenFile)

        self.iface.removePluginMenu("Landax", self.actionOpenFolder)
        QObject.disconnect(self.actionOpenFolder, SIGNAL("activated()"), self.open_folder)
        self.iface.removeToolBarIcon(self.actionOpenFolder)

        self.iface.removePluginMenu("Landax", self.actionShowSelectPatternDialog)
        QObject.disconnect(self.actionShowSelectPatternDialog, SIGNAL("activated()"), self.show_SelectPatternDialog)
        self.iface.removeToolBarIcon(self.actionShowSelectPatternDialog)

        self.iface.removePluginMenu("Landax", self.actionShowAboutDialog)
        QObject.disconnect(self.actionShowAboutDialog, SIGNAL("activated()"), self.show_AboutDialog)
        self.iface.removeToolBarIcon(self.actionShowAboutDialog)

        self.iface.removePluginMenu("Landax", self.actionShowObjectInfoDialog)
        QObject.disconnect(self.actionShowObjectInfoDialog, SIGNAL("activated()"), self.show_ObjectInfoDialog)
        self.iface.removeToolBarIcon(self.actionShowObjectInfoDialog)

    # Запускается при нажатии на кнопку в меню
    def hello_world(self):
        QMessageBox.information(self.iface.mainWindow(), QApplication.translate("Module name", "Landex"), QLocale.system().name())
        # тестовое сообщение окошко
        # QMessageBox.information(self.iface.mainWindow(), QCoreApplication.translate('тестовое сообщение', "landax2222222222"), QCoreApplication.translate('landax2222222222', "landax2222222222"))
        # self.dlgRoundCoords = DoDoc(self.iface)
        # self.dlgRoundCoords = DoDoc(self.iface)
        # self.dlgRoundCoords.__init__(self.iface)
        # self.dlgRoundCoords.doDocFromTemplate(self.iface)

        # self.dlgRoundCoords.show()
        # set_stiggers
        return

    def open_file(self):
        #  QFileDialog.getOpenFileName(QWidget parent=None,
        #                              QString caption=QString(),
        #                              QString directory=QString(),
        #                              QString filter=QString(),
        #                              QString selectedFilter=None,
        #                              QFileDialog.Options options=0)
        filenames = QFileDialog.getOpenFileNames(self.iface.mainWindow(), QApplication.translate("Toolbar", 'XML Exchange file selection'), '', '*.xml')
        for f in filenames:
            # QMessageBox.information(self.iface.mainWindow(), u"Landex", f)
            self.openXML(f)
        return

    def open_folder(self):
        self.dir = QFileDialog.getExistingDirectory(self.iface.mainWindow(), QApplication.translate("Toolbar", 'Folder with XML Exchange files selection'), self.dir)
        # TODO: сделать проверу на правильность выбранного пути (путь неверный, если нажали кнопку Отмена)
        #    QMessageBox.information(self.iface.mainWindow(), u"Landex", u'Папка не выбрана!')
        ans = QMessageBox.question(self.iface.mainWindow(), QApplication.translate("Module name", "Landex"), QApplication.translate("Toolbar", 'Search files recursively?'), QMessageBox.Yes | QMessageBox.No);

        for d, dirs, files in os.walk(self.dir):
            for f in files:
                if fnmatch.fnmatch(f, '*.xml'):
                    QMessageBox.information(self.iface.mainWindow(), QApplication.translate("Module name", "Landex"), os.path.join(d, f))
                    self.openXML(os.path.join(d, f))
            if ans == QMessageBox.No:
                return
        return

    def show_AboutDialog(self):
        ShowAbout(self.iface)
        return

    def show_SelectPatternDialog(self):
        str = GetPatternName(self.iface, False)
        if str == '' or str == None:
            QMessageBox.information(self.iface.mainWindow(), QApplication.translate("Module name", "Landex"), QApplication.translate("Toolbar", 'Pattern not selected!'))
        else:
            QMessageBox.information(self.iface.mainWindow(), QApplication.translate("Module name", "Landex"), str)
        return

    def openXML(self, file):
        # Логгирование средствами QGIS
        QgsMessageLog.logMessage('OpenXML', 'Landax')
        xml = ix.ImportXML()
        xml.prepare(file)
        d = Draw(self.iface)
        d.set_stiggers()
        pts = xml.getPoints()
        pln = xml.getPolylines()
        adjacentUnitsList=xml.getAdjacentUnits
        bouderyList = xml.getBoudary()
        
        idParcel=d.getParcelID()
        
        d.doDrawPoints(pts, idParcel)
        d.doDrawLines(pln, idParcel)

        d.writeToQgisLayer(bouderyList, idParcel)
        d.doDrawAdjacentUnits(adjacentUnitsList, idParcel)

    def show_ObjectInfoDialog(self):
        ShowObjectInfo(self.iface)
        return

if __name__ == "__main__":
    pass
